package com.rjkj.medicalwaste.ui.storage

import android.app.AlertDialog
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.paging.LoadState
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.rjkj.medicalwaste.MainActivity
import com.rjkj.medicalwaste.R
import com.rjkj.medicalwaste.adapter.ItemClick
import com.rjkj.medicalwaste.adapter.StorageMainAdapter
import com.rjkj.medicalwaste.base.BaseFragment
import com.rjkj.medicalwaste.bean.GarbageStatus
import com.rjkj.medicalwaste.bean.ReviewWeightState
import com.rjkj.medicalwaste.database.GarbageRequestUnReview
import com.rjkj.medicalwaste.database.GarbageSetUnReview
import com.rjkj.medicalwaste.databinding.FragmentStorageMainBinding
import com.rjkj.medicalwaste.livedatabus.LiveDataBus
import com.rjkj.medicalwaste.utils.StringUtils
import com.rjkj.medicalwaste.viewmodels.UnBoxedViewModel
import com.rjkj.medicalwaste.viewmodels.UserViewModel
import com.rjkj.medicalwaste.viewmodels.provider.MainViewModelProvider
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

class StorageMainFragment : BaseFragment<FragmentStorageMainBinding>() {
    private val unBoxedViewModel: UnBoxedViewModel by viewModels {
        MainViewModelProvider.provideUnBoxedModel(requireContext())
    }
    private val userViewModel: UserViewModel by activityViewModels {
        MainViewModelProvider.provideUserModel(requireContext())
    }
    private val testAdapter: StorageMainAdapter by lazy {
        StorageMainAdapter(object : ItemClick<GarbageRequestUnReview> {
            override fun onClicked(view: View, value: GarbageRequestUnReview) {
                if (value.garbageUserStatus == GarbageStatus.review) {
                    val builder = AlertDialog.Builder(requireActivity())
                    builder.setMessage("是否撤销")
                        .setPositiveButton("确定") { _, _ ->
                            lifecycleScope.launch {
                                unBoxedViewModel.updateGarbageSetUnReview(
                                    GarbageSetUnReview(
                                        id = value.id,
                                        garbageQRCode = value.garbageQRCode,
                                        garbageUserStatus = GarbageStatus.loading,
                                        reviewWeightState = ReviewWeightState.UnCheck
                                    )
                                )
//                                    value.garbageStatus = GarbageStatus.collect
//                                    value.reviewWeightState = ReviewWeightState.UnCheck
//                                    unBoxedViewModel.updateGarbageToTempBox(value, userViewModel.stagingRoomUser.value)
                            }
                        }
                        .setNegativeButton("取消") { _, _ ->

                        }
                    builder.create().show()
                } else {
                    if (userViewModel.setting.value?.review == true) {//复核模式
                        ReviewWeightDialog().apply {
                            val bundle = Bundle()
                            bundle.putString(BoxListFragment.GARBAGE_TYPE, value.garbageQRCode)
                            this.arguments = bundle
                            setStyle(
                                DialogFragment.STYLE_NORMAL,
                                R.style.dialogNormal
                            )//添加上面创建的style
                        }.show(parentFragmentManager, "ReviewWeightDialog")
                    } else {
                        UnReviewWeightDialog().apply {
                            val bundle = Bundle()
                            bundle.putString(BoxListFragment.GARBAGE_TYPE, value.garbageQRCode)
                            this.arguments = bundle
                            setStyle(
                                DialogFragment.STYLE_NORMAL,
                                R.style.dialogNormal
                            )//添加上面创建的style
                        }.show(parentFragmentManager, "UnReviewWeightDialog")
                    }


//                    val builder = AlertDialog.Builder(requireActivity())
//                    builder.setMessage("复核重量")
//                            .setPositiveButton("成功"
//                            ) { _, _ ->
//                                lifecycleScope.launch {
//                                    value.garbageStatus = GarbageStatus.loading
//                                    value.reviewWeightState = ReviewWeightState.CheckSuccess
//                                    unBoxedViewModel.updateGarbageToTempBox(value, userViewModel.stagingRoomUser.value)
//                                }
//                            }
//                            .setNegativeButton("失败"
//                            ) { _, _ ->
//                                lifecycleScope.launch {
//                                    value.garbageStatus = GarbageStatus.loading
//                                    value.reviewWeightState = ReviewWeightState.CheckFail
//                                    unBoxedViewModel.updateGarbageToTempBox(value, userViewModel.stagingRoomUser.value)
//                                }
//                            }
//                    builder.create().show()
                }

            }
        }, requireContext())
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val binding = FragmentStorageMainBinding.inflate(inflater, container, false)
        onSubscribeUi(binding)
        binding.lifecycleOwner = viewLifecycleOwner
        return binding.root
    }

    override fun onSubscribeUi(binding: FragmentStorageMainBinding) {
        initTip(userViewModel)
        testAdapter.addLoadStateListener {
            when (it.refresh) {
                is LoadState.Loading -> {
                    binding.spinner.isVisible = true
                    binding.list.isVisible = false
                    binding.imEmpty.isVisible = false
                }
                is LoadState.NotLoading -> {
                    binding.spinner.isVisible = false
                    if (testAdapter.snapshot().items.isEmpty()) {
                        binding.list.isVisible = false
                        binding.imEmpty.isVisible = true
                    } else {
                        binding.list.isVisible = true
                        binding.imEmpty.isVisible = false
                    }
                }
                is LoadState.Error -> {
                    binding.spinner.isVisible = false
                    binding.list.isVisible = false
                    binding.imEmpty.isVisible = true
                }
            }
        }
        binding.imBack.setOnClickListener {
            findNavController().navigateUp()
        }
        binding.list.apply {
            val dividerItemDecoration =
                DividerItemDecoration(requireContext(), DividerItemDecoration.VERTICAL)
            addItemDecoration(dividerItemDecoration)
            layoutManager = LinearLayoutManager(requireContext())
            adapter = testAdapter
        }
        binding.btGotoBox.setOnClickListener {
            findNavController().navigate(R.id.action_storageMainFragment_to_boxListFragment)
        }
//        viewModel.pageNum.observe(viewLifecycleOwner, Observer {
//            lifecycleScope.launch {
//                viewModel.getPagingData().collect {
//                    testAdapter.submitData(it)
//                }
//            }
//        })
//        binding.nextPage.setOnClickListener {
//            viewModel.pageNum.value = viewModel.pageNum.value?.plus(1)
//        }
//        binding.lastPage.setOnClickListener {
//            viewModel.pageNum.value = viewModel.pageNum.value?.minus(1)
//        }

//        binding.btCanbox.setOnClickListener{
//            findNavController().navigate(R.id.action_storageMainFragment_to_storageCanFragment)
//        }
//        binding.btBoxFinish.setOnClickListener{
//            findNavController().navigate(R.id.action_storageMainFragment_to_boxListFragment)
//        }

        userViewModel.hospitalId.value?.let {
            unBoxedViewModel.getStateGarbageByStoreCodeToList(
                it, GarbageStatus.loading, userViewModel.stagingRoomUser.value?.qrcode
                    ?: ""
            ).observe(viewLifecycleOwner, { list ->
                binding.tvNum.text = list.size.toString()
            })
        }
        lifecycleScope.launchWhenResumed {

            userViewModel.hospitalId.value?.let {
                unBoxedViewModel.repository.getAllGarbageRequestUnReview(
                    it,
                    userViewModel.stagingRoomUser.value?.qrcode ?: ""
                ).collectLatest {paging->
                    //TODO 需要优化
                    //弹窗不会影响当前的Fragment的可见情况
                    delay(300)
                    if (parentFragmentManager.fragments.last() is StorageMainFragment) {
                        Log.e(TAG, "submitData: ", )
                        testAdapter.submitData(paging)
                    }
                }
            }

        }


    }


}